package utils

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	
)



func EncAesKey(message string) string{

Pub_K := `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArr2FXPfKUcfS+WqJmqUW
yCpO6zDpM9BkU3XiIK8vQmcKGyugIpFre4yqeLnieseXHVNU4y6Wx90gwQ2Wy5fs
uc6/ADxJL8yWiWeDyr4tikzeHCGOqUzimHyFW0pA2ywzYIOrIKsKhvg50UnT8eDR
52iRz6K7xDvlCgpzJut7XTlLQAWTEypKBzL0ucGUd89u6MrzZOaexozlOoFBFfzV
66rcDoPW/jYuySgUmI6RErQwN3Xba4qR5y5jLm+2jp0qsK9+P2i9KKVb72f9TRx/
vvXQUssXi1McgT/p5pPm8Y9XCc3NJ7dlD2v3xZ08jPbFb2u3pD8LDJlPyh8hP6AG
VQIDAQAB
-----END PUBLIC KEY-----`
publicKey, err := ImportPublicKeyFromPEM([]byte(Pub_K))

	if err != nil {
		panic(err)
	}
	ciphertext, err := RSAEncrypt(publicKey, []byte(message))
	if err != nil {
		panic(err)
	}

	return string(ciphertext)
}


// RSAEncrypt 使用 RSA 公钥加密数据
func RSAEncrypt(publicKey *rsa.PublicKey, data []byte) ([]byte, error) {
	// 加密分块大小为密钥长度 - 2*哈希长度 - 2
	// 对于 2048 位密钥和 PKCS#1 v1.5，最大加密长度是 245 字节
	return rsa.EncryptPKCS1v15(rand.Reader, publicKey, data)
}

// RSADecrypt 使用 RSA 私钥解密数据
func RSADecrypt(privateKey *rsa.PrivateKey, ciphertext []byte) ([]byte, error) {
	return rsa.DecryptPKCS1v15(rand.Reader, privateKey, ciphertext)
}


func ImportPublicKeyFromPEM(pemBytes []byte) (*rsa.PublicKey, error) {
	block, _ := pem.Decode(pemBytes)
	
	

	pub, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, fmt.Errorf("failed to parse public key: %v", err)
	}
	return pub.(*rsa.PublicKey), nil
}

func ImportPrivateKeyFromPEM(pemBytes []byte) (*rsa.PrivateKey, error) {
	block, _ := pem.Decode(pemBytes)
	if block == nil || block.Type != "RSA PRIVATE KEY" {
		return nil, fmt.Errorf("failed to decode PEM block containing private key")
	}

	privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, fmt.Errorf("failed to parse private key: %v", err)
	}

	return privateKey, nil
}

// ExportPrivateKeyToPEM 将私钥转换为 PEM 格式
func ExportPrivateKeyToPEM(privateKey *rsa.PrivateKey) []byte {
	privateKeyBytes := x509.MarshalPKCS1PrivateKey(privateKey)
	privateKeyPEM := pem.EncodeToMemory(&pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: privateKeyBytes,
	})
	return privateKeyPEM
}

// ExportPublicKeyToPEM 将公钥转换为 PEM 格式
func ExportPublicKeyToPEM(publicKey *rsa.PublicKey) ([]byte, error) {
	publicKeyBytes, err := x509.MarshalPKIXPublicKey(publicKey)
	if err != nil {
		return nil, err
	}
	publicKeyPEM := pem.EncodeToMemory(&pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: publicKeyBytes,
	})
	return publicKeyPEM, nil
}
